<template>
  <div class="min-h-screen bg-gray-50">
    <!-- 顶部导航栏 -->
    <NavBar />
    
    <!-- 主内容区域 -->
    <div class="max-w-7xl mx-auto px-4 py-8">
      <!-- 横幅轮播区域 -->
      <Banner />

      <!-- 筛选区域 -->
      <div class="bg-white rounded-lg shadow-md p-6 mb-8">
            <div class="flex flex-wrap gap-4 items-center">
              <div class="flex-1 min-w-[300px]">
                <input
                  v-model="searchKeyword"
                  type="text"
                  placeholder="请输入书名或作者名"
                  class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-orange-500"
                  @keyup.enter="handleSearch"
                />
              </div>
              
              <select
                v-model="selectedCategory"
                class="px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary-500"
              >
                <option value="">全部分类</option>
                <option v-for="cat in categories" :key="cat.id" :value="cat.id">
                  {{ cat.name }} ({{ cat.novel_count }})
                </option>
              </select>
              
              <select
                v-model="selectedStatus"
                class="px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-orange-500"
              >
                <option value="">全部状态</option>
                <option :value="1">连载中</option>
                <option :value="2">已完结</option>
              </select>
              
              <button
                @click="handleSearch"
                class="btn-primary"
              >
                搜索
              </button>
              
              <button
                @click="toggleFeatured"
                :class="[
                  'px-6 py-2 rounded-lg transition-colors',
                  isFeaturedOnly 
                    ? 'bg-primary-500 text-white hover:bg-primary-600' 
                    : 'bg-gray-200 text-gray-700 hover:bg-gray-300'
                ]"
              >
                ⭐ 推荐
              </button>
            </div>
      </div>

      <!-- 加载状态 -->
      <div v-if="loading" class="text-center py-12">
        <div class="inline-block animate-spin rounded-full h-12 w-12 border-b-2 border-primary-500"></div>
        <p class="mt-4 text-gray-600">加载中...</p>
      </div>

      <!-- 小说列表 -->
      <div v-else-if="novels.length > 0" class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6">
        <NovelCard
          v-for="novel in novels"
          :key="novel.id"
          :novel="novel"
          @click="goToDetail(novel.id)"
        />
      </div>

      <!-- 空状态 -->
      <div v-else class="text-center py-12">
        <p class="text-gray-600">暂无数据</p>
      </div>

      <!-- 分页 -->
      <div v-if="pagination.total_pages > 1" class="flex justify-center mt-8">
        <div class="flex gap-2">
            <button
              @click="changePage(page - 1)"
              :disabled="page === 1"
              class="px-4 py-2 border border-gray-300 rounded-lg disabled:opacity-50 disabled:cursor-not-allowed hover:bg-gray-100 transition-colors"
            >
              上一页
            </button>
            
            <span class="px-4 py-2">
              第 {{ page }} / {{ pagination.total_pages }} 页
            </span>
            
            <button
              @click="changePage(page + 1)"
              :disabled="page === pagination.total_pages"
              class="px-4 py-2 border border-gray-300 rounded-lg disabled:opacity-50 disabled:cursor-not-allowed hover:bg-gray-100 transition-colors"
            >
              下一页
            </button>
        </div>
      </div>
    </div>
    <!-- AI对话侧边栏按钮与面板 -->
    <div class="fixed right-4 top-32 z-50">
      <button
        @click="showAIChat = !showAIChat"
        class="bg-orange-500 hover:bg-orange-600 text-white px-4 py-2 rounded-lg shadow-lg"
      >小说相关查找</button>

      <div v-if="showAIChat" class="mt-2 w-[440px] h-[560px] bg-white rounded-xl shadow-2xl border border-gray-200 flex flex-col overflow-hidden">
        <div class="px-4 py-3 bg-white border-b flex items-center justify-between">
          <div class="font-semibold text-gray-800">小说相关查找</div>
          <button @click="showAIChat=false" class="w-7 h-7 grid place-items-center rounded-md hover:bg-gray-100 text-gray-500">✕</button>
        </div>
        <!-- 评估指标Chip -->
        <div class="px-4 py-3 bg-gray-50 border-b text-xs text-gray-500">
          如有解决不了的问题，请联系在线客服
        </div>
        <div class="flex-1 overflow-y-auto p-4 space-y-3">
          <div v-if="aiMessages.length===0" class="text-center text-gray-400 py-10">请输入问题开始查询...</div>
          <div v-for="(m,idx) in aiMessages" :key="idx" class="space-y-2">
            <div class="px-3 py-2 rounded-md bg-blue-50 text-blue-800">问题：{{ m.question }}</div>
            <div v-if="m.loading" class="text-center text-gray-400">检索中...</div>
            <div v-if="m.error" class="text-red-600 text-sm text-center">{{ m.error }}</div>
            <div v-if="m.answer" class="p-3 rounded-lg border bg-orange-50 text-gray-800 whitespace-pre-line leading-6">
              <div class="text-sm font-semibold text-orange-700 mb-2">回答</div>
              {{ m.answer }}
            </div>
            <div v-if="hasMetrics(m.evaluation)" class="p-3 rounded-lg border bg-white text-xs text-gray-600 space-y-1">
              <div class="text-xs font-medium text-gray-500">评估指标</div>
              <div v-if="m.evaluation?.precision != null">精确率：{{ formatMetric(m.evaluation.precision) }}</div>
              <div v-if="m.evaluation?.recall != null">召回率：{{ formatMetric(m.evaluation.recall) }}</div>
              <div v-if="m.evaluation?.f1Score != null || m.evaluation?.f1_score != null">
                F1：{{ formatMetric(m.evaluation.f1Score ?? m.evaluation.f1_score) }}
              </div>
              <div v-if="m.evaluation?.accuracy != null">准确率：{{ formatMetric(m.evaluation.accuracy) }}</div>
            </div>
            <div v-if="m.sources && m.sources.length" class="p-3 rounded-lg border bg-white">
              <div class="text-xs font-medium text-gray-500 mb-2">参考来源</div>
              <ul class="list-disc list-inside space-y-1 text-xs text-gray-600">
                <li v-for="(src, i) in m.sources" :key="i">{{ src }}</li>
              </ul>
            </div>
          </div>
        </div>
        <div class="p-3 border-t bg-white flex gap-2">
          <input v-model="aiQuestion" @keyup.enter="handleAIQuery" class="flex-1 h-10 px-3 border rounded-lg focus:outline-none focus:ring-2 focus:ring-orange-500" placeholder="输入要查找的内容..."/>
          <button @click="handleAIQuery" :disabled="aiLoading || !aiQuestion.trim()" class="h-10 px-4 bg-orange-500 hover:bg-orange-600 text-white rounded-lg disabled:opacity-50">{{ aiLoading? '查询中...':'查询' }}</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, computed, nextTick } from 'vue'
import { storeToRefs } from 'pinia'
import { useRouter } from 'vue-router'
import { useNovelStore } from '@/stores/novel'
import { novelAPI } from '@/api/novel'
import api from '@/api'
import NavBar from '@/components/layout/NavBar.vue'
import NovelCard from '@/components/novel/NovelCard.vue'
import Banner from '@/components/layout/Banner.vue'

const router = useRouter()
const novelStore = useNovelStore()

// 使用Store中的响应式数据（保持响应性）
const { novels, categories, loading, pagination, filters } = storeToRefs(novelStore)

// 本地响应式数据
const searchKeyword = ref('')
const selectedCategory = ref('')
const selectedStatus = ref('')
const isFeaturedOnly = ref(false)

// AI对话
const showAIChat = ref(false)
const aiQuestion = ref('')
const aiLoading = ref(false)
const aiMessages = ref([])

// 当前页（从store的filters中读取）
const page = computed(() => filters.value.page)

// 获取分类列表
const fetchCategories = async () => {
  try {
    const res = await novelAPI.getCategories()
    novelStore.setCategories(res.data || [])
  } catch (error) {
    console.error('获取分类失败:', error)
  }
}

// 获取小说列表
const fetchNovels = async () => {
  novelStore.setLoading(true)
  try {
    // 更新筛选条件
    novelStore.updateFilter('keyword', searchKeyword.value)
    novelStore.updateFilter('category_id', selectedCategory.value)
    novelStore.updateFilter('status', selectedStatus.value)
    novelStore.updateFilter('is_featured', isFeaturedOnly.value)
    
    // 构造并清洗参数：去掉空字符串，数值型转为数字
    const raw = { ...filters.value }
    const params = {
      page: raw.page,
      page_size: raw.page_size,
      ...(raw.category_id !== '' && raw.category_id != null
        ? { category_id: Number(raw.category_id) }
        : {}),
      ...(raw.keyword ? { keyword: String(raw.keyword) } : {}),
      ...(raw.status !== '' && raw.status != null
        ? { status: Number(raw.status) }
        : {}),
      ...(raw.is_featured ? { is_featured: true } : {}),
    }
    
    const res = await novelAPI.getList(params)
    console.debug('novels list res:', res)
    novelStore.setNovels(res.data.list || [])
    novelStore.setPagination(res.data.pagination || {})
  } catch (error) {
    console.error('获取小说列表失败:', error)
    novelStore.setNovels([])
  } finally {
    novelStore.setLoading(false)
  }
}

// 搜索
const handleSearch = () => {
  novelStore.updateFilter('page', 1)
  fetchNovels()
}

// 切换推荐
const toggleFeatured = () => {
  isFeaturedOnly.value = !isFeaturedOnly.value
  novelStore.updateFilter('page', 1)
  fetchNovels()
}

// 切换分页
const changePage = (newPage) => {
  if (newPage >= 1 && newPage <= pagination.total_pages) {
    novelStore.updateFilter('page', newPage)
    fetchNovels()
  }
}

// 跳转到详情页
const goToDetail = (novelId) => {
  router.push(`/novel/${novelId}`)
}

// 发起AI查询
const handleAIQuery = async () => {
  const q = aiQuestion.value.trim()
  if (!q || aiLoading.value) return
  const msg = { question: q, answer: '', sources: [], evaluation: null, loading: true, error: null }
  aiMessages.value.push(msg)
  aiQuestion.value = ''
  aiLoading.value = true
  await nextTick()
  try {
    const res = await api.post(`/RAG/select?question=${encodeURIComponent(q)}`)
    const ragData = res.data || {}
    msg.loading = false
    if (ragData.answer) {
      msg.answer = ragData.answer
      msg.sources = Array.isArray(ragData.sources) ? ragData.sources : []
      const evalData = ragData.evaluation || {}
      msg.evaluation = {
        precision: evalData.precision ?? evalData.精确率 ?? null,
        recall: evalData.recall ?? evalData.召回率 ?? null,
        f1Score: evalData.f1Score ?? evalData.f1_score ?? evalData.F1值 ?? null,
        accuracy: evalData.accuracy ?? evalData.准确率 ?? null,
      }
    } else if (ragData.normalized_results) {
      const texts = ragData.normalized_results
        .map((item) => item?.text || '')
        .filter((text) => text)
      if (texts.length) {
        msg.answer = texts.join('\n\n')
      }
      const evalData = ragData.evaluation || {}
      msg.evaluation = {
        precision: evalData.precision ?? evalData.精确率 ?? null,
        recall: evalData.recall ?? evalData.召回率 ?? null,
        f1Score: evalData.f1Score ?? evalData.f1_score ?? evalData.F1值 ?? null,
        accuracy: evalData.accuracy ?? evalData.准确率 ?? null,
      }
    } else {
      msg.error = '未获取到结果'
      msg.evaluation = null
    }
  } catch (e) {
    msg.loading = false
    console.error('RAG查询错误:', e)
    msg.error = e?.response?.data?.message || e.message || '查询失败'
    msg.evaluation = null
  } finally {
    aiLoading.value = false
  }
}

const hasMetrics = (metrics) => {
  if (!metrics) return false
  return ['precision', 'recall', 'f1Score', 'f1_score', 'accuracy'].some((key) => {
    const value = metrics[key]
    return value !== null && value !== undefined
  })
}

const formatMetric = (val) => {
  if (val === null || val === undefined) return '--'
  const num = Number(val)
  if (Number.isNaN(num)) return String(val)
  return num.toFixed(3)
}

// 监听筛选条件变化
watch([selectedCategory, selectedStatus], () => {
  novelStore.updateFilter('page', 1)
  fetchNovels()
})

// 初始化
onMounted(() => {
  fetchCategories()
  fetchNovels()
})
</script>

<style scoped>
/* 自定义样式 */
</style>

